import axios from 'axios';
import { getToken } from '@/utils/auth.js';
import { showSuccessToast, showFailToast } from 'vant';

const service = axios.create({
    baseURL: '/mock/book',
    timeout: 5000
});
// 请求拦截器
service.interceptors.request.use(config => {
    // Do something before request is sent
    config.headers['token'] = getToken();
    return config;
}, error => {
    // Do something with request error
    console.log(error);
    return Promise.reject(error);
});
// 响应拦截器
service.interceptors.response.use(res => {
    // Do something with response data
    // console.log(res);
    const { data } = res;
    if (typeof data !== 'object') {
        console.log(data);
        showFailToast('服务器异常，请联系管理员');
        return Promise.reject(res);
    }
/*     if (data.code != 200) {
        if (res.data.message) {
            console.error(res.data.message)
            // showFailToast(res.data.message)
        }
        return Promise.reject(res.data);
    } */
    return data;
}, error => {
    // 这里用来处理http常见错误，进行全局提示
    let message = "";
    switch (error.response.status) {
        case 400:
            message = "请求错误(400)";
            break;
        case 401:
            message = "未授权，请重新登录(401)";
            // 这里可以做清空storage并跳转到登录页的操作
            break;
        case 403:
            message = "拒绝访问(403)";
            break;
        case 404:
            message = "请求出错(404)";
            break;
        case 408:
            message = "请求超时(408)";
            break;
        case 500:
            message = "服务器错误(500)";
            break;
        case 501:
            message = "服务未实现(501)";
            break;
        case 502:
            message = "网络错误(502)";
            break;
        case 503:
            message = "服务不可用(503)";
            break;
        case 504:
            message = "网络超时(504)";
            break;
        case 505:
            message = "HTTP版本不受支持(505)";
            break;
        default:
            message = `连接出错(${err.response.status})!`;
    }
    // 这里错误消息可以使用全局弹框展示出来
    showFailToast(message);
    // 这里是AxiosError类型，所以一般我们只reject我们需要的响应即可
    console.log(error);
    return Promise.reject(error);
});

export default service;